﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Text;
using Gateway;
using System.Web.Security;
using tenpay;
/// <summary>
/// Summary description for TuanService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消对下行的注释。    
[System.Web.Script.Services.ScriptService]
public class TuanService : System.Web.Services.WebService {

    public TuanService () {
        //Uncomment the following line if using designed components 
        //InitializeComponent();
    }

    [WebMethod]
    public bool HelloWorld() {
        return false;
    }

    #region  Order
    [WebMethod(Description = "订单支付")]
    public string OrderWaitPayWay(string oid,string pay_method)
    {
        // pay_method = "1"; //Request["pay_method"];
         //oid = "8";// Request["oid"];
        string Result = "";
        if (!string.IsNullOrEmpty(pay_method))
        {
            Tuan.Model.OrderInfo obj = (new Tuan.BLL.OrderInfo()).GetWaitPayModel(int.Parse(oid));
            switch (pay_method)
            {
                case "1"://支付宝
                   Result = (this.GoAliPay(obj));
                    break;
                case "2": // 财付通
                    Result = this.GoTenPay(obj);
                    break;
                case "3": 
                    break;
                default:
                    break;
            }
        }
        return Result;
    }

    protected string GoAliPay(Tuan.Model.OrderInfo orderObj)
    {
        //按时构造订单号；

        //System.DateTime currentTime = new System.DateTime();
        //currentTime = System.DateTime.Now;
        //string out_trade_no = currentTime.ToString("g");
        //out_trade_no = out_trade_no.Replace("-", "");
        //out_trade_no = out_trade_no.Replace(":", "");
        //out_trade_no = out_trade_no.Replace(" ", "");
        string out_trade_no = orderObj.OrderNum;
        //业务参数赋值；
        string gateway = "https://www.alipay.com/cooperate/gateway.do?";	//'支付接口
        string service = "create_direct_pay_by_user";
        string partner = "2088302319713223";		//partner		合作伙伴ID			保留字段
        string sign_type = "MD5";
        string subject = orderObj.ProductName;	//subject		商品名称
        string body = string.Format("OrderID:{0},{1}",orderObj.OrderNum,orderObj.ProductName);		//body			商品描述    
        string payment_type = "1";                  //支付类型	
        string total_fee = orderObj.PayMoney.ToString();                      //总金额					0.01～50000.00
        string show_url = "http://www.alipay.com/"; ;
        string seller_email = "tuan51@yeah.net";                //卖家账号
        string key = "pl0426ygo5ah1gpvfmlhc0kh2xk20110";              //partner账户的支付宝安全校验码
        //服务器通知url（Alipay_Notify.aspx文件所在路经），必须是完整的路径地址
        string notify_url = "http://5151tuan.com/pages/PayWay/Alipay/Alipay_Notify.aspx";
        //服务器返回url（Alipay_Return.aspx文件所在路经），必须是完整的路径地址
        string return_url = "http://5151tuan.com/pages/PayWay/Alipay/Alipay_Return.aspx";
        string _input_charset = "utf-8";
        AliPay ap = new AliPay();
        string aliay_url = ap.CreatUrl(
            gateway,
            service,
            partner,
            sign_type,
            out_trade_no,
            subject,
            body,
            payment_type,
            total_fee,
            show_url,
            seller_email,
            key,
            return_url,
            _input_charset,
            notify_url
            );
        //写入日志   
        StringBuilder meg = new StringBuilder("\r\n开始支付:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ";订单号:" + orderObj.OrderNum + ";向支付宝发送支付请求,url:" + aliay_url);
        //try
        //{
        //    //更新订单
        //    meg.AppendLine("数据库写入成功!");
        //}
        //catch (Exception ex)
        //{
        //    meg.AppendLine("数据库写入失败:");
        //    meg.Append(ex.Message);
        //}
        Pan.Log.WriteLog(meg.ToString(),"AliPay");
        return aliay_url;
        
        // Response.Redirect(aliay_url);
    }

    protected string GoTenPay(Tuan.Model.OrderInfo orderObj)
    {
        //商户号
        string bargainor_id = "1206083201";

        //密钥
        string key = "a788fb0d0c15259488fe26cb397ee2af";

        //当前时间 yyyyMMdd
        string date = DateTime.Now.ToString("yyyyMMdd");

        //生成订单10位序列号，此处用时间和随机数生成，商户根据自己调整，保证唯一
        string strReq = "" + DateTime.Now.ToString("HHmmss") + TenpayUtil.BuildRandomStr(4);

        //商户订单号，不超过32位，财付通只做记录，不保证唯一性
        string sp_billno = orderObj.OrderNum;

        //财付通订单号，10位商户号+8位日期+10位序列号，需保证全局唯一
        string transaction_id = bargainor_id + date + strReq;
        string return_url = "http://5151tuan.com/pages/PayWay/tenpay/Tenpay_Return.aspx";

        //创建PayRequestHandler实例
        PayRequestHandler reqHandler = new PayRequestHandler(Context);

        //设置密钥
        reqHandler.setKey(key);

        //初始化
        reqHandler.init();

        //-----------------------------
        //设置支付参数
        //-----------------------------
        reqHandler.setParameter("bargainor_id", bargainor_id);			//商户号
        reqHandler.setParameter("sp_billno", sp_billno);				//商家订单号
        reqHandler.setParameter("transaction_id", transaction_id);		//财付通交易单号
        reqHandler.setParameter("return_url", return_url);				//支付通知url
        reqHandler.setParameter("desc",orderObj.ProductName);	//商品名称
        //reqHandler.setParameter("total_fee", "1");						//商品金额,以分为单位  测试
        reqHandler.setParameter("total_fee", ((orderObj.PayMoney * 100)).ToString().TrimEnd('0').TrimEnd('.'));						//商品金额,以分为单位

        //用户ip,测试环境时不要加这个ip参数，正式环境再加此参数
        //reqHandler.setParameter("spbill_create_ip",Page.Request.UserHostAddress);

        //获取请求带参数的url
        string requestUrl = reqHandler.getRequestURL();
        StringBuilder meg = new StringBuilder("\r\n开始支付:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ";订单号:" + orderObj.OrderNum + ";向支付宝发送支付请求,url:" + requestUrl);
       
        Pan.Log.WriteLog(meg.ToString(), "TenPay");
        return requestUrl;
    }

    
    [WebMethod(Description="新订单")]
    public int CreateOrder(int pid, string pname, decimal price, int count, int token, int freight, string name, string tel,string add, decimal pay,int uid)
    {
        int orderid=0;
        try
        {
            decimal totalMoney = price * count + freight;
            decimal payMoney = totalMoney - token;
            if (pay == payMoney)
            {
                Tuan.Model.OrderInfo obj = new Tuan.Model.OrderInfo();
                obj.ProductID = pid;
                obj.ProductName = pname;
                obj.Price = price;
                obj.Count = count;
                obj.CheckName = name;
                obj.Freight = freight;
                obj.PayMoney = payMoney;
                obj.Token = token;
                obj.UserID = uid;
                obj.TotalAmount = totalMoney;
                obj.Tel = tel;
                obj.CheckAddress = add;

                orderid = (new Tuan.BLL.OrderInfo()).Add(obj);
            }
        }
        catch (Exception e)
        {
            Pan.Log.WriteLog(e.Message, "CreateOrder");
        }

        return orderid;
    }

    [WebMethod(Description = "删除订单‘")]
    public bool DeleteOrder(int orderid)
    {
       int flag= (new Tuan.BLL.OrderInfo()).Delete(orderid);//非物理删除订单
       if (flag > 0)
           return true;
       else
           return false;
    }
    
    #endregion

    #region UCENTER
    [WebMethod(Description = "检查EMAIL是否唯一")]
    public bool CheckEmail(string email)
    {
        MembershipUserCollection col = Membership.FindUsersByName(email);
        if (col.Count != 0)
        {
           return true;
        }
        return false;
    }
    [WebMethod(Description="检查昵称是否唯一")]
    public string CheckName(string nickname)
    {
        return nickname;
    }

    [WebMethod(Description = "用户订阅邮件")]
    public bool UserSubMail(string cityid,string email)
    {
        Tuan.Model.SubInfo model = new Tuan.Model.SubInfo();
        model.CityID = Convert.ToInt32(cityid);
        model.Email = email;
        model.SubType =2;
        int flag = (new Tuan.BLL.SubInfo()).Add(model);
        if (flag > 0)
            return true;
        return false;
    }

    [WebMethod(Description = "添加地址")]
    public int UserNewAddress(string uid,string signer,string address,string tel,string zip)
    {
        return 1;
    }

    #endregion

    #region Shop
    [WebMethod(Description="发表评论")]
    public bool ReviewNew(string uid, string pid, string body, string pname)
    {
        try
        {
            Tuan.Model.Review obj = new Tuan.Model.Review();
            obj.Body = System.Web.HttpUtility.UrlDecode(body);
            obj.ProductID = int.Parse(pid);
            obj.UserID = (new Tuan.BLL.UserInfo()).GetModelByCache(uid).UserID;
            obj.ProductName = pname;
            (new Tuan.BLL.Review()).Add(obj);
            
        }
        catch
        {
            return false;
        }
        return true;
    }

    [WebMethod(Description = "获取当日销售产品")]
    public System.Collections.ArrayList ProductTodayGet(string cityid)
    {
        Pan.Log.WriteLog("又来了");
        Tuan.Model.Products producObj = (new Tuan.BLL.Products()).GetWebServiceModle(cityid);
        System.Collections.ArrayList arr = new System.Collections.ArrayList();
        arr.Add(producObj.ProductID.ToString());
        arr.Add(producObj.ProductName);
        arr.Add(producObj.Des);
        arr.Add(producObj.Feature);
        //Tuan.Model.Products producObj = (new Tuan.BLL.Products()).GetWebServiceModle(cityid);
        //obj.Add("productid", producObj.ProductID.ToString());
        //obj.Add("productname", producObj.ProductName);
        return arr;
    }
    [WebMethod(Description="获取购买人数")]
    public string ProductRefurbish(int pid, int minNum,int maxNum,string endDate)
    {
      
        StringBuilder strShow = new StringBuilder();
        try
        {
            int tarededcount = (new Tuan.BLL.OrderInfo()).GetTradedCount(pid);
            DateTime pDate = Convert.ToDateTime(endDate);
            DateTime dtNow = DateTime.Parse(DateTime.Now.ToShortDateString());
            if (maxNum > 0 && tarededcount >= maxNum)
            {
                string str = "<div  class=\"index_one_l_left_cont6\" style='background-color:#e4e1eb' tag='已经卖光'><img src='/app_themes/ftuan/images/bg-sold-out.gif' alt='已经卖光' /><p style='font-size:12pt;margin-top:10px; text-align:center;font-weight:bold;with:100%'>共有{0}人购买</p></div>";
                return string.Format(str,maxNum);
            }
               
            strShow.AppendFormat("<div class=\"index_one_l_left_cont6\"><div class=\"index_one_l_left_cont6_t f14\">{0}人已买</div>", tarededcount);
            if (dtNow <= pDate)
            {
                strShow.Append("<div class=\"tipometer\"><img src='/app_themes/ftuan/images/index_g1.gif' alt='已经成团' /></div>");
                if (maxNum > 0 && tarededcount < maxNum)
                {
                    strShow.AppendFormat("<div class=\"index_one_l_left_cont6_b\">目前产品剩余<font style='color:red'>{0}件</font></div></div>",maxNum-tarededcount);
                }
                else if (minNum <= 0)
                {
                    strShow.Append("<div class=\"index_one_l_left_cont6_b\">无最低团购人数限制</div></div>");
                }
                else if (tarededcount >= minNum)
                {
                    DateTime dt = DateTime.Now.AddHours(-2);
                    object obj = (new Tuan.BLL.OrderInfo()).GetReachMinNumber(pid, minNum - 1);
                    if (obj != null)
                        dt = Convert.ToDateTime(obj);
                    strShow.AppendFormat("<div class=\"index_one_l_left_cont6_b\">{0}达到最低购买人数{1}人;</div></div>", dt.ToString("HH:mm"), minNum);
                }
                else
                {
                    //strShow.Append("<div class=\"tipometer\"><img src='/app_themes/ftuan/images/index_g1.gif' alt='速度抢购' /></div>");
                    strShow.AppendFormat("<div class=\"index_one_l_left_cont6_b\">最低成团购买人数需{0}人</div></div>", minNum);
                }
            }
            else
            {
                strShow.Append("<div class=\"tipometer\"><img src='/app_themes/ftuan/images/index_g3.gif' alt='已經結束' /></div>");
                strShow.AppendFormat("<div class=\"index_one_l_left_cont6_b\">最低成团购买人数需{0}人</div></div>", minNum);
            }
        }
        catch (Exception e)
        {
            Pan.Log.WriteLog(e.Message, "App_Code");
        }
        //if (tarededcount >= minNum)
        //{

        //    DateTime dt = DateTime.Parse((new Tuan.BLL.OrderInfo()).GetReachMinNumber(pid,minNum-1));
            
         
        //    if (dtNow <= pDate)
        //    {
        //        strShow.Append("<div class=\"tipometer\"><img src='/app_themes/ftuan/images/index_g1.gif' alt='已经成团' /></div>");
        //    }
        //    else
        //    {
        //        strShow.Append("<div class=\"tipometer\"><img src='/app_themes/ftuan/images/index_g3.gif' alt='已經結束' /></div>");
        //    }

        //        strShow.AppendFormat("<div class=\"index_one_l_left_cont6_b\">{0}达到最低购买人数{1}人;</div></div>", dt.ToString("HH:mm"), minNum);
        //}
        //else
        //{
        //    strShow.Append("<div class=\"tipometer\"><img src='/app_themes/ftuan/images/index_g1.gif' alt='速度抢购' /></div>");
        //    strShow.AppendFormat("<div class=\"index_one_l_left_cont6_b\">最低成团购买人数需{0}人</div></div>", minNum);
      
        //}      
        return strShow.ToString(); ;
    }
    #endregion



}

